
package com.koala.common.security.util;


import cn.hutool.core.util.StrUtil;
import com.koala.common.core.utils.SecurityConstants;
import com.koala.common.security.service.KoalaUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

@UtilityClass//把普通类转为工具类
public  class  SecurityUtils {

       private Authentication getAuthentication(){ return SecurityContextHolder.getContext().getAuthentication(); }

       public KoalaUser getUser(){
           Object principal = getAuthentication().getPrincipal();
           if (principal==null) {
               return  null;
           }else {
               if (principal instanceof KoalaUser) {
                   return (KoalaUser) principal;
               }else{
                   return null;
               }
           }
       }

       public List<Integer> getRoles(){
           Collection<? extends GrantedAuthority> authorities = getAuthentication().getAuthorities();
           ArrayList<Integer> roles = new ArrayList<>();
           authorities.stream()
                   .filter(granted -> StrUtil.startWith( granted.getAuthority(), SecurityConstants.ROLE))
                   .forEach(granted -> {
                       String id=StrUtil.removePrefix( granted.getAuthority(),SecurityConstants.ROLE);
                           roles.add(Integer.parseInt(id));
                   }
                   );
           return roles;
       }
}

